//
//  WalletDetailViewController.swift
//  Wallet
//
//  Created by Julian on 2022/5/7.
//

import UIKit
import RxSwift

/// 为了考虑页面复用，拆分了 WalletDetail 和 CoinList，都是项目中可能多出需要使用的
class WalletDetailViewController: UIViewController {
    @IBOutlet weak var totalSymbolLabel: UILabel!
    @IBOutlet weak var totalAmountLabel: UILabel!
    @IBOutlet weak var currencyLabel: UILabel!
    
    var viewModel: WalletViewModel?
    let bag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    // FIXME: - 目前没有想到比较好的方案，目的是 HomeViewController 管理一份 ViewModel，子控制器不在对 viewModel 进行操作，但是子控制器的 viewDidLoad 早于主控制器
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard let vc = self.parent as? HomeViewController else {
            return
        }
        self.setupBinding(vm: vc.viewModel)
    }
}

// MARK: - 界面数据绑定
extension WalletDetailViewController {
    func setupBinding(vm: WalletViewModel) {
        self.viewModel = vm
        viewModel?.totalAmount
            .map { String(format: "%0.2f", $0) }
            .bind(to: totalAmountLabel.rx.text)
            .disposed(by: bag)
        
        AppSettings.shared.currency
            .asDriver(onErrorJustReturn: CurrencyType.USD)
            .map { $0 == CurrencyType.USD ? "$" : "HK$" }
            .drive(totalSymbolLabel.rx.text)
            .disposed(by: bag)
        
        AppSettings.shared.currency
            .asDriver(onErrorJustReturn: CurrencyType.USD)
            .map { $0 == CurrencyType.USD ? "USD" : "HKD" }
            .drive(currencyLabel.rx.text)
            .disposed(by: bag)
    }
}
